﻿#include "Riskgis.h"
#include<QObject>
#include "./ui_Riskgis.h"
#include<qgslayertreenode.h>
#include<qgslayertreemodel.h>
#include<qgsrasterlayer.h>
#include<qgsvectorlayer.h>
#include<qgsmaplayer.h>
#include <qgslayertreeviewdefaultactions.h>
#include<qgsprocessingtoolboxtreeview.h>//test
//
#include"rgslayertreeviewmenuprovider.h"
#include<qgsgui.h>
#include<qgseditorwidgetregistry.h>
#include<qgstransaction.h>
#include<qgstransactiongroup.h>
#include<qgssettingsregistrycore.h>
#include<qgsmessageviewer.h>
#include<QgsVertexMarker.h>
#include<qgsvectorlayerproperties.h>
//

#include"rgsattributetable.h"
#include"rgsmaptooladdfeature.h"

//
#include<QFileDialog>
#include<QMessageBox>
#include<QToolButton>
Riskgis* Riskgis::rgs_instance=0;
Riskgis::Riskgis(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow),mMapCanvas(this),mLayerTreeView(this),mapcanvas_crs(0)
{
    rgs_instance=this;
    ui->setupUi(this);
    _Panels=new QMenu(this);
    setDockOptions( dockOptions() | QMainWindow::GroupedDragging );
    setCorner(Qt::BottomLeftCorner,Qt::LeftDockWidgetArea);
    setCorner(Qt::BottomRightCorner,Qt::RightDockWidgetArea);
    //setDockNestingEnabled(true);
    //QgsApplication::initQgis();


    //暂时未与其他模块无联系的类--初始化

    //未设置父组件，需要显式释放
    mVectorLayerTools=new QgsGuiVectorLayerTools();



    //--

    initMessageLogViewer();
    inittreeviewdock();
    initMapCanvas();
    initfiledock();
    updateCanvasLayer();

    initAdvanceDigitizingDockWidget();
    createMapTools();
    initstatusbar();


    mMapCanvas.zoomToFullExtent();
    mMapCanvas.setMapTool(m_mapToolPan,false);

    //注册属性表代理编辑控件
    QgsGui::editorWidgetRegistry()->initEditors(&mMapCanvas,m_infoBar);


    //允许窗口可以拖入文件
    this->setAcceptDrops(true);
    initformatlist();




    // 连接地图画布和图层管理器
    layerTreeCanvasBridge = new QgsLayerTreeMapCanvasBridge(QgsProject::instance()->layerTreeRoot(), &mMapCanvas, this);
    riskcreatoverview();

    connect(QgsProject::instance(), SIGNAL(writeProject(QDomDocument&)),
            layerTreeCanvasBridge, SLOT(writeProject(QDomDocument&)));
    connect(QgsProject::instance(), SIGNAL(readProject(QDomDocument)),
            layerTreeCanvasBridge, SLOT(readProject(QDomDocument)));


    resize(1500,1200);
    setTitle();
    test_qgsfunction();
    //QString title="test";
    //QString message="应用打开成功";
    //emit emitmessage(title,message);
}

Riskgis::~Riskgis()
{
    delete ui;
    delete mVectorLayerTools;
}

void Riskgis::updateCanvasLayer()
{
    mMapCanvas.setLayers(((QgsLayerTreeNode*)(QgsProject::instance()->layerTreeRoot()))->checkedLayers());
    mMapCanvas.refresh();
}

void Riskgis::inittreeviewdock()
{
    QgsLayerTree* pLayerTreeRoot = QgsProject::instance()->layerTreeRoot();
    QObject::connect((QgsLayerTreeNode*)pLayerTreeRoot, &QgsLayerTreeNode::visibilityChanged, this, &Riskgis::updateCanvasLayer);
    QgsLayerTreeModel* pLayerTreeModel = new QgsLayerTreeModel(pLayerTreeRoot);

    pLayerTreeModel->setFlag(QgsLayerTreeModel::AllowNodeChangeVisibility);
    pLayerTreeModel->setFlag( QgsLayerTreeModel::AllowNodeRename );
    pLayerTreeModel->setFlag( QgsLayerTreeModel::AllowNodeReorder );
    pLayerTreeModel->setFlag( QgsLayerTreeModel::ShowLegendAsTree );

    mLayerTreeView.setModel(pLayerTreeModel);
    mLayerTreeView.setMaximumWidth(400);  // 设置一下最大宽度以便给画布留出更多显示空间
    mLayerTreeView.setMenuProvider(new rgslayertreeviewmenuprovider(&mLayerTreeView,&mMapCanvas));

    QToolButton* btnAddGroup = new QToolButton(this);
    btnAddGroup->setAutoRaise(true);
    btnAddGroup->setIcon(QIcon(":/images/themes/default/mActionAddGroup.svg"));
    btnAddGroup->setFixedSize(24, 24);
    btnAddGroup->setToolTip(tr("Add Group"));
    connect(btnAddGroup, SIGNAL(clicked()), mLayerTreeView.defaultActions(), SLOT(addGroup()));

    // expand / collapse tool buttons
    QToolButton* btnExpandAll = new QToolButton(this);
    btnExpandAll->setAutoRaise(true);
    btnExpandAll->setIcon(QIcon(":/images/themes/default/mIconExpand.svg"));
    btnAddGroup->setFixedSize(24, 24);
    btnExpandAll->setToolTip(tr("Expand All"));
    connect(btnExpandAll, SIGNAL(clicked()), mLayerTreeView.defaultActions(), SLOT(expandAll()));

    QToolButton* btnCollapseAll = new QToolButton(this);
    btnCollapseAll->setAutoRaise(true);
    btnCollapseAll->setIcon(QIcon(":/images/themes/default/mActionCollapseTree.svg"));
    btnAddGroup->setFixedSize(24, 24);
    btnCollapseAll->setToolTip(tr("Collapse All"));
    connect(btnCollapseAll, SIGNAL(clicked()), mLayerTreeView.defaultActions(), SLOT(collapseAll()));

    // remove item button
    QToolButton* btnRemoveItem = new QToolButton(this);
    // btnRemoveItem->setDefaultAction( this->m_actionRemoveLayer );
    btnRemoveItem->setAutoRaise(true);
    btnRemoveItem->setIcon(QIcon(":/images/themes/default/mActionRemove.svg"));
    btnAddGroup->setFixedSize(24, 24);
    btnRemoveItem->setToolTip(tr("Remove"));
    connect(btnRemoveItem, SIGNAL(clicked()), mLayerTreeView.defaultActions(), SLOT(remove()));

    // 按钮布局
    QHBoxLayout* toolbarLayout = new QHBoxLayout();
    toolbarLayout->setContentsMargins(QMargins(5, 0, 5, 0));
    toolbarLayout->addWidget(btnAddGroup);
    toolbarLayout->addWidget(btnCollapseAll);
    toolbarLayout->addWidget(btnExpandAll);
    toolbarLayout->addWidget(btnRemoveItem);
    toolbarLayout->addStretch();

    QVBoxLayout* vboxLayout = new QVBoxLayout();
    vboxLayout->setMargin(0);
    vboxLayout->addLayout(toolbarLayout);
    vboxLayout->addWidget(&mLayerTreeView);




    treeviewdock=new QgsDockWidget(tr("Layers"),this);
    treeviewdock->setObjectName("Layers");
    //treeviewdock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);

    QWidget* w = new QWidget(this);
    w->setLayout(vboxLayout);
    treeviewdock->setWidget(w);
    addDockWidget(Qt::LeftDockWidgetArea, treeviewdock);
    treeviewdock->resize(this->frameGeometry().width()/2,this->frameGeometry().height());
    treeviewdock->setMaximumWidth(400);
}

void Riskgis::initMapCanvas()
{
    mMapCanvas.setProject( QgsProject::instance() );
    // 给一个默认的地图范围
    QgsRectangle* defaultExtent = new QgsRectangle( -1, -1, 1, 1 );
    mMapCanvas.setExtent( *defaultExtent );

    m_infoBar=new QgsMessageBar(this);
    m_infoBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
    QWidget* centralWidget = this->centralWidget();
    //释放原有布局
    //centralWidget->setLayout(nullptr);
    //centralWidget->setLayout()


    QGridLayout* centralLayout = new QGridLayout();
    centralLayout->setContentsMargins(0,0,0,0);


    m_stackedWidget = new QStackedWidget( this );

    m_stackedWidget->addWidget( &mMapCanvas );


    centralLayout->addWidget( m_stackedWidget, 0, 0, 1, 1 );
    centralLayout->addWidget( m_infoBar, 1, 0, 1, 1 );

    centralWidget->setLayout(centralLayout);

    QObject::connect(this,&Riskgis::emitmessage,m_infoBar,&QgsMessageBar::pushInfo);

}

void Riskgis::initMessageLogViewer()
{
    messagedock=new QgsDockWidget(u8"message",this);
    general=new QgsMessageLogViewer(this);
    messagedock->setWidget(general);
    //messagedock->setAllowedAreas(Qt::AllDockWidgetAreas);

    addDockWidget(Qt::BottomDockWidgetArea,messagedock);
    QgsMessageLog::logMessage("message",QString(),Qgis::Info);
    //QgsMessageLog::logMessage("message","second",Qgis::Info);

}

void Riskgis::createMapTools()
{
    m_mapToolPan = new QgsMapToolPan(&mMapCanvas);
    m_mapToolZoomIn = new QgsMapToolZoom( &mMapCanvas, false );
    m_mapToolZoomOut = new QgsMapToolZoom( &mMapCanvas, true );
    m_mapToolIdentify = new Rgsmaptoolidentifyaction( &mMapCanvas );
    m_mapToolAddFeature = new RgsMapToolAddFeature(&mMapCanvas,cadDockWidget(),QgsMapToolCapture::CapturePolygon);
    auto toolgroup=new QActionGroup(this);
    toolgroup->addAction(ui->actionMapToolPan);
    toolgroup->addAction(ui->actionzoomin);
    toolgroup->addAction(ui->actionzoomout);
    toolgroup->addAction(ui->actionmActionIdentify);
    toolgroup->setExclusive(true);
}

void Riskgis::initfiledock()
{
    //QgsApplication::processingRegistry()->addProvider( new QgsNativeAlgorithms( QgsApplication::processingRegistry() ) );
    QgsDockWidget* tem=new QgsDockWidget(this);
    //QgsProcessingToolboxModel* processingtooboxmodel=new QgsProcessingToolboxModel(this,QgsApplication::processingRegistry());
    QgsProcessingToolboxTreeView* processingtoolboxview=new QgsProcessingToolboxTreeView(this,QgsApplication::processingRegistry());
    //QgsProcessingToolboxProxyModel * processingtoolboxproxymodel=new QgsProcessingToolboxProxyModel(this,QgsApplication::processingRegistry());
    //源码中这样
    //processingtoolboxview->setToolboxProxyModel((QgsProcessingToolboxProxyModel*)(processingtooboxmodel));
    //processingtoolboxview->setToolboxProxyModel(processingtoolboxproxymodel);
    //processingtoolboxview->setModel(processingtooboxmodel);

    connect(processingtoolboxview,&QgsProcessingToolboxTreeView::doubleClicked,this,[=](){
        qDebug()<<"双击工具箱";
        //processingtoolboxview->selectionModel()->clear();
        if ( processingtoolboxview->selectedAlgorithm() ){
            qDebug()<<"双击到算法";
            qDebug()<<processingtoolboxview->selectedAlgorithm()->id();
            qDebug()<<processingtoolboxview->selectedAlgorithm()->name();
        }


    });
    tem->setWidget(processingtoolboxview);
    tem->setWindowTitle(tr("Processing Toolbox"));
    addDockWidget(Qt::RightDockWidgetArea,tem);

    //QgsApplication::dataItemProviderRegistry()->addProvider( new QgsProjectDataItemProvider() );
    mBrowserModel = new QgsBrowserGuiModel( this );
    mBrowserWidget = new QgsBrowserDockWidget( tr( "Browser" ), mBrowserModel, this );
    mBrowserWidget->setObjectName( QStringLiteral( "Browser" ) );
    mBrowserWidget->setMessageBar( m_infoBar );
    addDockWidget( Qt::RightDockWidgetArea, mBrowserWidget );
    _Panels->addAction(mBrowserWidget->toggleViewAction());
}

void Riskgis::initstatusbar()
{
    QFont myFont( "Arial", 9 );
    xcoordinates=new QLineEdit(this);
    xcoordinates->setFont(myFont);
    ycoordinates=new QLineEdit(this);
    ycoordinates->setFont(myFont);
    xcoordinates->setFixedWidth(150);
    ycoordinates->setFixedWidth(150);
    xlabel=new QLabel(this);
    xlabel->setText("x");
    xlabel->setFont(myFont);
    ylabel=new QLabel(this);
    ylabel->setText("y");
    ylabel->setFont(myFont);

    m_scaleLabel=new QLabel(this);
    m_scaleLabel->setFont(myFont);
    m_scaleLabel->setMinimumWidth( 10 );
    m_scaleLabel->setMargin( 3 );
    m_scaleLabel->setAlignment( Qt::AlignCenter );
    m_scaleLabel->setFrameStyle( QFrame::NoFrame );
    m_scaleLabel->setText( tr( "Scale" ) );
    m_scaleLabel->setToolTip( tr( "Current map scale" ) );


    ui->statusbar->addPermanentWidget(xlabel);
    ui->statusbar->addPermanentWidget(xcoordinates);
    ui->statusbar->addPermanentWidget(ylabel);
    ui->statusbar->addPermanentWidget(ycoordinates);
    m_scaleEdit=new QgsScaleComboBox(this);
    m_scaleEdit->setObjectName( "m_scaleEdit" );
    m_scaleEdit->setFont( myFont );
    m_scaleEdit->setMinimumWidth( 10 );
    m_scaleEdit->setMaximumWidth( 150 );
    m_scaleEdit->setContentsMargins( 0, 0, 0, 0 );
    m_scaleEdit->setToolTip( tr( "Current map scale (formatted as x:y)" ) );

    ui->statusbar->addPermanentWidget( m_scaleLabel);
    ui->statusbar->addPermanentWidget( m_scaleEdit);


    m_progressBar=new QProgressBar(this);
    m_progressBar->setObjectName( "m_progressBar" );
    m_progressBar->setMaximumWidth(100);
    //m_progressBar->hide();
    ui->statusbar->addPermanentWidget( m_progressBar);
    //ui->statusbar->showMessage("test...",3000);

    QObject::connect(&mMapCanvas,&QgsMapCanvas::xyCoordinates,this,&Riskgis::showMousePoint);
    QObject::connect(m_scaleEdit, &QgsScaleComboBox::scaleChanged, this, &Riskgis::userScale);
    QObject::connect( &mMapCanvas, SIGNAL( scaleChanged( double ) ), this, SLOT( showScale( double ) ) );
}

void Riskgis::riskcreatoverview()
{
    // overview canvas
    this->m_overviewcanvas = new QgsMapOverviewCanvas( nullptr, &mMapCanvas );

    //set canvas color to default
    QgsSettings settings;
    int red = settings.value( QStringLiteral( "qgis/default_canvas_color_red" ), 255 ).toInt();
    int green = settings.value( QStringLiteral( "qgis/default_canvas_color_green" ), 255 ).toInt();
    int blue = settings.value( QStringLiteral( "qgis/default_canvas_color_blue" ), 255 ).toInt();
    m_overviewcanvas->setBackgroundColor( QColor( red, green, blue ) );

    this->m_overviewmapcursor = new QCursor( Qt::OpenHandCursor );
    this->m_overviewcanvas->setCursor( *m_overviewmapcursor);
    cc=new QgsDockWidget(this);
    //cc->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    cc->setWidget(m_overviewcanvas);
    addDockWidget(Qt::LeftDockWidgetArea,cc);
    ui->menu->addAction(cc->toggleViewAction());
    layerTreeCanvasBridge->setOverviewCanvas(m_overviewcanvas);
    //m_overviewcanvas->setLayers(layers);
    //m_overviewcanvas->refresh();
}

void Riskgis::initAdvanceDigitizingDockWidget()
{
    mAdvancedDigitizingDockWidget = new QgsAdvancedDigitizingDockWidget( &mMapCanvas, this );
    mAdvancedDigitizingDockWidget->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea);
    addDockWidget(Qt::RightDockWidgetArea,mAdvancedDigitizingDockWidget);
    mAdvancedDigitizingDockWidget->setWindowTitle( tr( "Advanced Digitizing" ) );
    mAdvancedDigitizingDockWidget->hide();
    _Panels->setTitle(QString(tr("Panels")));
    ui->menuview->addMenu(_Panels);
    _Panels->addAction(mAdvancedDigitizingDockWidget->toggleViewAction());
}

void Riskgis::setTitle()
{
    QString name="Rgis";
    QString filename=QgsProject::instance()->fileName();
    if (filename.isNull())
    {
        name=name+"-"+"未命名";
    }else {
        name=name+"-"+QFileInfo(filename).completeBaseName();
    }
    setWindowTitle(name);
}

void Riskgis::closeProject()
{
    saveDirty();	// 保存修改

    mMapCanvas.setLayers( QList<QgsMapLayer *>() );
    mMapCanvas.clearCache();
    mMapCanvas.cancelJobs();
    m_overviewcanvas->setLayers( QList<QgsMapLayer *>() );

    mLayerTreeView.setCurrentIndex( QModelIndex() );
    QgsProject::instance()->clear();

}

void Riskgis::markDirty()
{
    QgsProject::instance()->setDirty(true);
}

void Riskgis::saveDirty()
{
    bool dirty=QgsProject::instance()->isDirty();
    mMapCanvas.freeze(true);
    QMessageBox::StandardButton result(QMessageBox::Discard);
    if(dirty){
        result=QMessageBox::information(
            this,
            tr("保存"),
            tr("项目已被修改，是否保存"),
            QMessageBox::Save|QMessageBox::Cancel|QMessageBox::Discard,
            QMessageBox::Save);
        if(result==QMessageBox::Save){
            saveProject();
        }

    }
    mMapCanvas.freeze(false);
}

bool Riskgis::saveProject()
{
    // 如果没有项目文件路径，提示用户选择路径
    if(QgsProject::instance()->fileName().isNull())
    {
        QFileInfo fullPath;
        QString path = QFileDialog::getSaveFileName(
            this,
            tr("选择QGis项目的保存位置"),
            NULL,
            tr("QGIS files") + " (*.qgs *.QGS)");

        if(path.isEmpty())
            return false;

        fullPath.setFile(path);
        if ("qgs" != fullPath.suffix().toLower())
        {
            fullPath.setFile(fullPath.filePath() + ".qgs");
        }

        QgsProject::instance()->setFileName(fullPath.filePath());
    }
    else
    {
        QFileInfo fi(QgsProject::instance()->fileName());

        // 检查是否可写
        if(fi.exists() && !fi.isWritable())
        {
            QMessageBox::critical(this, tr("错误"), tr("无法保存项目文件。"));
            return false;
        }
    }

    setTitle();
    // 写文件
    return QgsProject::instance()->write();
}

void Riskgis::dragEnterEvent(QDragEnterEvent *event)
{
    QList< QUrl> urs;
    urs = event->mimeData()->urls();
    // 判断是否存在可打开的文件
    for (int i=0;i<urs.size();i++)
    {
        QFileInfo fileInfo(urs[i].toLocalFile());
        if (formatList.contains(fileInfo.suffix()))
        {
            event->acceptProposedAction();
            break;
        }
        event->ignore();
    }
}

void Riskgis::dropEvent(QDropEvent *event)
{
    QList< QUrl> urs;
    urs = event->mimeData()->urls();
    for (int i = 0; i < urs.size(); i++)
    {
        QFileInfo fileInfo(urs[i].toLocalFile());
        if (formatList.contains(fileInfo.suffix()))
        {
            if ("tif" == fileInfo.suffix())
            {
                addrasterlayer(fileInfo.filePath());// 打开qgs与qgz文件
            }
            else if("shp" == fileInfo.suffix())
            {
                addvectorlayer(fileInfo.filePath());// 打开矢量或栅格图层
            }
            else
            {

            }
        }
    }
}

void Riskgis::histogramStretch(bool visibleAreaOnly, QgsRasterMinMaxOrigin::Limits limits)
{
    QgsMapLayer *myLayer = mLayerTreeView.currentLayer();

    if ( !myLayer )
    {
        visibleMessageBar()->pushMessage( tr( "No Layer Selected" ),
                                         tr( "To perform a full histogram stretch, you need to have a raster layer selected." ),
                                         Qgis::MessageLevel::Info );
        return;
    }

    QgsRasterLayer *myRasterLayer = qobject_cast<QgsRasterLayer *>( myLayer );
    if ( !myRasterLayer )
    {
        visibleMessageBar()->pushMessage( tr( "No Layer Selected" ),
                                         tr( "To perform a full histogram stretch, you need to have a raster layer selected." ),
                                         Qgis::MessageLevel::Info );
        return;
    }

    QgsRectangle myRectangle;
    if ( visibleAreaOnly )
        myRectangle = mMapCanvas.mapSettings().outputExtentToLayerExtent( myRasterLayer, mMapCanvas.extent() );

    myRasterLayer->setContrastEnhancement( QgsContrastEnhancement::StretchToMinimumMaximum, limits, myRectangle );

    myRasterLayer->triggerRepaint();
}

QgsMessageBar *Riskgis::visibleMessageBar()
{
    return m_infoBar;
}

void Riskgis::adjustBrightnessContrast(int delta, bool updateBrightness)
{
    const auto constSelectedLayers = mLayerTreeView.selectedLayers();
    for ( QgsMapLayer *layer : constSelectedLayers )
    {
        if ( !layer )
        {
            visibleMessageBar()->pushMessage( tr( "No Layer Selected" ),
                                             tr( "To change brightness or contrast, you need to have a raster layer selected." ),
                                             Qgis::MessageLevel::Info );
            return;
        }

        QgsRasterLayer *rasterLayer = qobject_cast<QgsRasterLayer *>( layer );
        if ( !rasterLayer )
        {
            visibleMessageBar()->pushMessage( tr( "No Layer Selected" ),
                                             tr( "To change brightness or contrast, you need to have a raster layer selected." ),
                                             Qgis::MessageLevel::Info );
            return;
        }

        QgsBrightnessContrastFilter *brightnessFilter = rasterLayer->brightnessFilter();

        if ( updateBrightness )
        {
            brightnessFilter->setBrightness( brightnessFilter->brightness() + delta );
        }
        else
        {
            brightnessFilter->setContrast( brightnessFilter->contrast() + delta );
        }

        rasterLayer->triggerRepaint();
    }
}

void Riskgis::adjustGamma(double delta)
{
    const auto constSelectedLayers = mLayerTreeView.selectedLayers();
    for ( QgsMapLayer *layer : constSelectedLayers )
    {
        if ( !layer )
        {
            visibleMessageBar()->pushMessage( tr( "No Layer Selected" ),
                                             tr( "To change gamma, you need to have a raster layer selected." ),
                                             Qgis::MessageLevel::Info );
            return;
        }

        QgsRasterLayer *rasterLayer = qobject_cast<QgsRasterLayer *>( layer );
        if ( !rasterLayer )
        {
            visibleMessageBar()->pushMessage( tr( "No Layer Selected" ),
                                             tr( "To change gamma, you need to have a raster layer selected." ),
                                             Qgis::MessageLevel::Info );
            return;
        }

        QgsBrightnessContrastFilter *brightnessFilter = rasterLayer->brightnessFilter();
        brightnessFilter->setGamma( brightnessFilter->gamma() + delta );

        rasterLayer->triggerRepaint();
    }
}

void Riskgis::test_qgsfunction()
{
    qDebug()<<QDir::homePath()<<"\n";
    QgsSettings settings;
    QString lastUsedDir = settings.value( QStringLiteral( "UI/lastProjectDir" ), QDir::homePath() ).toString();
    qDebug()<<lastUsedDir<<"\n";
    qDebug()<<QgsProject::instance()->title();
}

void Riskgis::initformatlist()
{
    formatList << "tif" << "tiff"  << "shp" << "qgs" << "qgz" << "jpg" << "png" << "bmp";
}

void Riskgis::addrasterlayer(QString filename)
{
    QFileInfo fi( filename );
    QString basename = fi.baseName();
    QgsRasterLayer* rasterLayer = new QgsRasterLayer( filename, basename, "gdal");
    if ( !rasterLayer->isValid() )
    {
        QMessageBox::critical( this, "error", "layer is invalid" );
        return;
    }
    if(mapcanvas_crs==0)
    {
        //设置画布的坐标系为图层坐标
        mMapCanvas.setDestinationCrs(rasterLayer->crs());
        mapcanvas_crs=1;
    }
    QgsProject::instance()->addMapLayer( rasterLayer );
    //mMapCanvas.setExtent(rasterLayer->extent());     //将画布范围设置为栅格图层范围
    layers.append(rasterLayer);                     //将栅格图层追加到链表中
    mLayerTreeView.setCurrentLayer(rasterLayer);
    mMapCanvas.setLayers(mLayerTreeView.selectedLayers());                    //将图层画到画布上
    //m_overviewcanvas->setLayers(mLayerTreeView.selectedLayers());
    //m_overviewcanvas->refresh();
    mMapCanvas.setVisible(true);
    mMapCanvas.freeze(false);
    //mMapCanvas.setExtent(rasterLayer->extent());
    //mMapCanvas.setExtent(mMapCanvas.extent());
    //mMapCanvas.zoomToPreviousExtent();
    mMapCanvas.refresh();
}

void Riskgis::addvectorlayer(QString filename)
{
    QFileInfo fi(filename );
    QString basename = fi.baseName();
    QgsVectorLayer* vecLayer = new QgsVectorLayer(filename, basename, "ogr");

    if (!vecLayer->isValid())
    {
        QMessageBox::critical(this, "error", QString("layer is invalid: \n") + filename);
        return;
    }
    if(mapcanvas_crs==0)
    {
        //设置画布的坐标系为图层坐标
        mMapCanvas.setDestinationCrs(vecLayer->crs());
        mapcanvas_crs=1;
    }
    //QGIS 3注册方式
    QgsProject::instance()->addMapLayer(vecLayer);
    //mLayerTreeView.sel

    mLayerTreeView.setCurrentLayer(vecLayer);




    //mMapCanvas.setExtent(vecLayer->extent());
    layers.append(vecLayer);
    mMapCanvas.setLayers(mLayerTreeView.selectedLayers());
    //m_overviewcanvas->setLayers(mLayerTreeView.selectedLayers());
    //m_overviewcanvas->refresh();
    mMapCanvas.setVisible(true);
    mMapCanvas.freeze(false);
    //mMapCanvas.setExtent(vecLayer->extent());
    //mMapCanvas.zoomToFullExtent();
    mMapCanvas.refresh();
}

bool Riskgis::toggleEditing(QgsMapLayer *layer)
{
    if(layer==nullptr){
        if(activeLayer()==nullptr)
            return false;
        else
            layer=activeLayer();
    }
    if(!layer->supportsEditing()){
        return false;
    }
    switch (layer->type()) {
    case QgsMapLayerType::VectorLayer:
        return toggleEditingVectorLayer(dynamic_cast<QgsVectorLayer*>(layer));
        break;
    case QgsMapLayerType::RasterLayer:
        break;
    case QgsMapLayerType::MeshLayer:
        break;
    default:
        break;
    }
    return false;
}

bool Riskgis::toggleEditingVectorLayer(QgsVectorLayer *vlayer)
{
    if ( !vlayer )
    {
        return false;
    }
    bool res = true;

    QSet<QgsVectorLayer *> modifiedLayers;
    switch ( QgsProject::instance()->transactionMode() )
    {
    case Qgis::TransactionMode::Disabled:
    {
        if ( vlayer->isModified() )
            modifiedLayers.insert( vlayer );
    }
    break;
    case Qgis::TransactionMode::AutomaticGroups:
    {
        QString connString = QgsTransaction::connectionString( vlayer->source() );
        QString key = vlayer->providerType();

        QMap< QPair< QString, QString>, QgsTransactionGroup *> transactionGroups = QgsProject::instance()->transactionGroups();
        QMap< QPair< QString, QString>, QgsTransactionGroup *>::iterator tIt = transactionGroups .find( qMakePair( key, connString ) );
        QgsTransactionGroup *tg = ( tIt != transactionGroups.end() ? tIt.value() : nullptr );

        if ( tg && tg->layers().contains( vlayer ) && tg->modified() )
        {
            if ( vlayer->isModified() )
                modifiedLayers.insert( vlayer );
            const QSet<QgsVectorLayer *> transactionGroupLayers = tg->layers();
            for ( QgsVectorLayer *iterLayer : transactionGroupLayers )
            {
                if ( iterLayer != vlayer && iterLayer->isModified() )
                    modifiedLayers.insert( iterLayer );
            }
        }
    }
    break;
    case Qgis::TransactionMode::BufferedGroups:
        modifiedLayers = QgsProject::instance()->editBufferGroup()->modifiedLayers();
        break;
    }



if ( !vlayer->isEditable() && !vlayer->readOnly() )
  {
    if ( !vlayer->supportsEditing() )
    {
      //mActionToggleEditing->setChecked( false );
      //mActionToggleEditing->setEnabled( false );
      visibleMessageBar()->pushMessage( tr( "Start editing failed" ),
                                        tr( "Provider cannot be opened for editing" ),
                                        Qgis::MessageLevel::Warning );
      return false;
    }

    QgsProject::instance()->startEditing( vlayer );

    QString markerType = QgsSettingsRegistryCore::settingsDigitizingMarkerStyle.value();
    bool markSelectedOnly = QgsSettingsRegistryCore::settingsDigitizingMarkerOnlyForSelected.value();

    // redraw only if markers will be drawn
    if ( ( !markSelectedOnly || vlayer->selectedFeatureCount() > 0 ) &&
         ( markerType == QLatin1String( "Cross" ) || markerType == QLatin1String( "SemiTransparentCircle" ) ) )
    {
      vlayer->triggerRepaint();
    }
  }
  else if ( modifiedLayers.size() > 0 )
  {
    bool allowCancel=true;
    QMessageBox::StandardButtons buttons = QMessageBox::Save | QMessageBox::Discard;
    if ( allowCancel )
      buttons |= QMessageBox::Cancel;

    QString modifiedLayerNames;
    if ( modifiedLayers.size() == 1 )
      modifiedLayerNames = ( *modifiedLayers.constBegin() )->name();
    else if ( modifiedLayers.size() == 2 )
      modifiedLayerNames = tr( "%1 and %2" ).arg( ( *modifiedLayers.constBegin() )->name(), ( * ++modifiedLayers.constBegin() )->name() );
    else if ( modifiedLayers.size() > 2 )
      modifiedLayerNames = tr( "%1, %2, …" ).arg( ( *modifiedLayers.constBegin() )->name(), ( * ++modifiedLayers.constBegin() )->name() );

    switch ( QMessageBox::question( nullptr,
                                    tr( "Stop Editing" ),
                                    modifiedLayers.size() > 0 ?
                                    tr( "Do you want to save the changes to layers %1?" ).arg( modifiedLayerNames ) :
                                    tr( "Do you want to save the changes to layer %1?" ).arg( modifiedLayerNames ),
                                    buttons ) )
    {
      case QMessageBox::Cancel:
        res = false;
        break;

      case QMessageBox::Save:
      {
        QApplication::setOverrideCursor( Qt::WaitCursor );

        QStringList commitErrors;
        if ( !QgsProject::instance()->commitChanges( commitErrors, true, vlayer ) )
        {
          commitError( vlayer, commitErrors );
          // Leave the in-memory editing state alone,
          // to give the user a chance to enter different values
          // and try the commit again later
          res = false;
        }

        vlayer->triggerRepaint();

        QApplication::restoreOverrideCursor();
      }
      break;

      case QMessageBox::Discard:
      {
        QApplication::setOverrideCursor( Qt::WaitCursor );

        //QgsCanvasRefreshBlocker refreshBlocker;

        QStringList rollBackErrors;
        if ( ! QgsProject::instance()->rollBack( rollBackErrors, true, vlayer ) )
        {
          visibleMessageBar()->pushMessage( tr( "Error" ),
                                            tr( "Problems during roll back: '%1'" ).arg( rollBackErrors.join( " / " ) ),
                                            Qgis::MessageLevel::Critical );
          res = false;
        }

        vlayer->triggerRepaint();

        QApplication::restoreOverrideCursor();
        break;
      }

      default:
        break;
    }
  }
  else //layer not modified
  {
    //QgsCanvasRefreshBlocker refreshBlocker;

    QStringList rollBackErrors;
    QgsProject::instance()->rollBack( rollBackErrors, true, vlayer );

    res = true;
    vlayer->triggerRepaint();
  }


  return res;
}

void Riskgis::commitError(QgsVectorLayer *vlayer, const QStringList &commitErrorsList)
{
  QStringList commitErrors = commitErrorsList;
  if ( vlayer && commitErrors.isEmpty() )
    commitErrors = vlayer->commitErrors();

  if ( vlayer && !vlayer->allowCommit() && commitErrors.empty() )
  {
    return;
  }

  const QString messageText = vlayer ? tr( "Could not commit changes to layer %1" ).arg( vlayer->name() )
                                     : tr( "Could not commit changes" );

  QgsMessageViewer *mv = new QgsMessageViewer();
  mv->setWindowTitle( tr( "Commit Errors" ) );
  mv->setMessageAsPlainText( messageText
                            + "\n\n"
                            + tr( "Errors: %1\n" ).arg( commitErrors.join( QLatin1String( "\n  " ) ) )
                            );

  QToolButton *showMore = new QToolButton();
  QAction *act = new QAction( showMore );
  act->setText( tr( "Show more" ) );
  showMore->setStyleSheet( QStringLiteral( "background-color: rgba(255, 255, 255, 0); color: black; text-decoration: underline;" ) );
  showMore->setCursor( Qt::PointingHandCursor );
  showMore->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred );
  showMore->addAction( act );
  showMore->setDefaultAction( act );
  connect( showMore, &QToolButton::triggered, mv, &QDialog::exec );
  connect( showMore, &QToolButton::triggered, showMore, &QObject::deleteLater );

  // no timeout set, since notice needs attention and is only shown first time layer is labeled
  QgsMessageBarItem *errorMsg = new QgsMessageBarItem(
      tr( "Commit errors" ),
      messageText,
      showMore,
      Qgis::MessageLevel::Warning,
      0,
      messageBar() );
  messageBar()->pushItem( errorMsg );
}

QgsMessageBar *Riskgis::messageBar()
{
  return m_infoBar;
}

QgsLayerTreeView *Riskgis::GetLayerTreeView()
{
    return &mLayerTreeView;
}

QgsMapCanvas *Riskgis::mapCanvas()
{
    return &mMapCanvas;
}

void Riskgis::attributeTable(QgsAttributeTableFilterModel::FilterMode filter, const QString &filterExpression)
{
    QgsVectorLayer *myLayer = qobject_cast<QgsVectorLayer *>( activeLayer() );
    qDebug()<<"图层判断";
    if ( !myLayer || !myLayer->dataProvider() )
    {
        return;
    }
    qDebug()<<"create table";
    try {
        rgsattributetable *mDialog = new rgsattributetable( myLayer, &mMapCanvas, filter, Qt::Window, nullptr, filterExpression );
        qDebug()<<"attritube table create success";
        mDialog->show();
    } catch (...) {
        qDebug()<<"...";
        qDebug()<<QgsError().message();
    }
//    rgsattributetable *mDialog = new rgsattributetable( myLayer, &mMapCanvas, filter, Qt::Window, nullptr, filterExpression );
//    qDebug()<<"attritube table create success";
//    mDialog->show();
}

QgsMapLayer *Riskgis::activeLayer()
{
    //qDebug()<<"activateLayer";
    return &mLayerTreeView ? mLayerTreeView.currentLayer() : nullptr;
}

void Riskgis::activateDeactivateRelatedAction(QgsMapLayer *layer)
{
    if(layer==nullptr)
        return;
    //Action激活或取消逻辑

    //
    QString addFeatureText;
    switch (layer->type()){
    case QgsMapLayerType::VectorLayer:{
        QgsVectorLayer* vlayer=dynamic_cast<QgsVectorLayer*>(layer);

/*
    enum GeometryType
    {
      PointGeometry,
      LineGeometry,
      PolygonGeometry,
      UnknownGeometry,
      NullGeometry
    };
*/
        if(vlayer->geometryType()==QgsWkbTypes::PointGeometry){
            ui->mActionAddFeature->setIcon(QIcon(":/images/themes/default/mActionCapturePoint.svg"));
            addFeatureText = tr( "Add Point Feature" );
        }
        else if(vlayer->geometryType()==QgsWkbTypes::LineGeometry){
            ui->mActionAddFeature->setIcon(QIcon(":/images/themes/default/mActionCaptureLine.svg"));
            addFeatureText = tr( "Add Line Feature" );
        }
        else if(vlayer->geometryType()==QgsWkbTypes::PolygonGeometry){
            ui->mActionAddFeature->setIcon(QIcon(":/images/themes/default/mActionCapturePolygon.svg"));
            addFeatureText = tr( "Add Polygon Feature" );
        }
        else if(vlayer->geometryType()==QgsWkbTypes::NullGeometry){

        }
        else{

        }
        ui->mActionAddFeature->setText(addFeatureText);
        if(vlayer->isEditable())
            ui->mActionAddFeature->setEnabled(true);
        else
            ui->mActionAddFeature->setEnabled(false);
        break;
    }
    default:
        break;
    }
}

QgsAdvancedDigitizingDockWidget *Riskgis::cadDockWidget()
{
    return mAdvancedDigitizingDockWidget;
}

void Riskgis::freezeCanvases(bool frozen)
{
    const auto canvases = mapCanvases();
    for ( QgsMapCanvas *canvas : canvases )
    {
        canvas->freeze( frozen );
    }
}

QList<QgsMapCanvas *> Riskgis::mapCanvases()
{
    auto canvases = findChildren< QgsMapCanvas * >();
    canvases.erase( std::remove_if( canvases.begin(), canvases.end(),
                                  []( QgsMapCanvas * canvas )
                                  {
                                      return !canvas || canvas->property( "browser_canvas" ).toBool();
                                  } ), canvases.end() );
    return canvases;
}

QgsAttributeEditorContext Riskgis::createAttributeEditorContext()
{
    QgsAttributeEditorContext context;
    context.setVectorLayerTools( vectorLayerTools() );
    context.setMapCanvas( mapCanvas() );
    context.setCadDockWidget( cadDockWidget() );
    context.setMainMessageBar( messageBar() );
    return context;
}



void Riskgis::on_actionaddRasterLayers_triggered()
{
    QString filename = QFileDialog::getOpenFileName( this, tr( "open vector" ), "",
                                                    "image(*.jpg *.png *.bmp);;remote sensing image(*.tif)" );
    if ( filename == "" ) { return; }
    addrasterlayer(filename);
}


void Riskgis::on_actionaddVectorLayers_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open shape file"), "", "*.shp");
    if (fileName.isNull()) //如果文件未选择则返回
    {
        return;
    }
    addvectorlayer(fileName);
}


void Riskgis::on_actionRemoveGroupOrLayer_triggered()
{
    QgsMapLayer* eraselayer=mLayerTreeView.currentLayer();
    if(eraselayer)
    {
        QList<QgsMapLayer*>::Iterator it=layers.begin();
        while (it!=layers.end())
        {
            if(eraselayer==*it)
            {
                layers.erase(it);
                break;
            }
            else
            {
                it++;
            }
        }

    }
    else
    {

    }
    mLayerTreeView.defaultActions()->actionRemoveGroupOrLayer()->triggered();
}


void Riskgis::on_actionRenameGroupOrLayer_triggered()
{
     mLayerTreeView.defaultActions()->actionRenameGroupOrLayer()->triggered();
}


void Riskgis::on_actionMapToolPan_toggled(bool arg1)
{
    if(arg1)
    {
        mMapCanvas.setMapTool(m_mapToolPan);
    }
    else
    {
        mMapCanvas.unsetMapTool(m_mapToolPan);
    }
}

void Riskgis::showMousePoint(const QgsPointXY &p)
{
    if (layers.empty())
    {
        // QgsLayerTreeView 为空
        return;
    }
    else
    {
        // QgsLayerTreeView 不为空
        xcoordinates->setText(QString::number(p.x(), 'f', 5));
        ycoordinates->setText(QString::number(p.y(), 'f', 5));
    }
}

void Riskgis::userScale()
{
    //qDebug()<<m_scaleEdit->scale();
    mMapCanvas.zoomScale(m_scaleEdit->scale());
    //mMapCanvas.refresh();
}

void Riskgis::showScale(double theScale)
{
    m_scaleEdit->setScale(  theScale/1.0 );
    if ( m_scaleEdit->width() > m_scaleEdit->minimumWidth() )
    {
        m_scaleEdit->setMinimumWidth( m_scaleEdit->width() );
    }
}


void Riskgis::on_actionopenattributeTable_triggered()
{
    if(mLayerTreeView.selectedLayers().empty())
    {
        return;
    }
    QgsMapLayer* vlayer=mLayerTreeView.currentLayer();
    QgsVectorLayer* vector=dynamic_cast<QgsVectorLayer*>(vlayer);
    if(vector)
    {
        //QgsAttributeTableDialog *mDialog = new QgsAttributeTableDialog( myLayer, filter, nullptr, Qt::Window, nullptr, filterExpression );
        //mDialog->show();
    }
}


void Riskgis::on_actionzoomin_toggled(bool arg1)
{
    if(arg1)
    {
        mMapCanvas.setMapTool(m_mapToolZoomIn);
    }
    else
    {
        mMapCanvas.unsetMapTool(m_mapToolZoomIn);
    }
}


void Riskgis::on_actionzoomout_toggled(bool arg1)
{
    if(arg1)
    {
        mMapCanvas.setMapTool(m_mapToolZoomOut);
    }
    else
    {
        mMapCanvas.unsetMapTool(m_mapToolZoomOut);
    }
}


void Riskgis::on_actionzoomfull_triggered()
{
    mMapCanvas.zoomToProjectExtent();
}


void Riskgis::on_actionlocalCumulativeCutStretch_triggered()
{
    histogramStretch( true, QgsRasterMinMaxOrigin::CumulativeCut );
}


void Riskgis::on_actionfullCumulativeCutStretch_triggered()
{
    histogramStretch( false, QgsRasterMinMaxOrigin::CumulativeCut );
}


void Riskgis::on_actionlocalHistogramStretch_triggered()
{
    histogramStretch( true, QgsRasterMinMaxOrigin::MinMax );
}


void Riskgis::on_actionfullHistogramStretch_triggered()
{
    histogramStretch( false, QgsRasterMinMaxOrigin::MinMax );
}


void Riskgis::on_actionincreaseBrightness_triggered()
{
    int step = 1;
    if ( QgsApplication::keyboardModifiers() == Qt::ShiftModifier )
    {
        step = 10;
    }
    adjustBrightnessContrast( step );
}


void Riskgis::on_actiondecreaseBrightness_triggered()
{
    int step = -1;
    if ( QgsApplication::keyboardModifiers() == Qt::ShiftModifier )
    {
        step = -10;
    }
    adjustBrightnessContrast( step );
}


void Riskgis::on_actionincreaseContrast_triggered()
{
    int step = 1;
    if ( QgsApplication::keyboardModifiers() == Qt::ShiftModifier )
    {
        step = 10;
    }
    adjustBrightnessContrast( step, false );
}


void Riskgis::on_actiondecreaseContrast_triggered()
{
    int step = -1;
    if ( QgsApplication::keyboardModifiers() == Qt::ShiftModifier )
    {
        step = -10;
    }
    adjustBrightnessContrast( step, false );
}


void Riskgis::on_actionincreaseGamma_triggered()
{
    double step = 0.1;
    if ( QgsApplication::keyboardModifiers() == Qt::ShiftModifier )
    {
        step = 1.0;
    }
    adjustGamma( step );
}


void Riskgis::on_actiondecreaseGamma_triggered()
{
    double step = -0.1;
    if ( QgsApplication::keyboardModifiers() == Qt::ShiftModifier )
    {
        step = -1.0;
    }
    adjustGamma( step );
}


void Riskgis::on_actionattributetable_triggered()
{
    attributeTable();
}



#include "rgsvertextool.h"

void Riskgis::on_actionmActionIdentify_toggled(bool arg1)
{
    if(arg1){
        mMapCanvas.setMapTool(m_mapToolIdentify);

    }else{
        mMapCanvas.unsetMapTool(m_mapToolIdentify);
    }
}


void Riskgis::on_actionspecialtest_triggered()
{
    qDebug()<<QgsProject::instance()->crs().description();
    QgsVectorLayer* vec=dynamic_cast<QgsVectorLayer*>(activeLayer());
    if(vec==nullptr)
    {
        return;
    }

    static RgsVertexTool* vertexMapTool=new RgsVertexTool(&mMapCanvas,mAdvancedDigitizingDockWidget);
    mMapCanvas.setMapTool(vertexMapTool);
    //QgsVectorLayerProperties* vectorlayerproperties=new QgsVectorLayerProperties(&mMapCanvas,messageBar(),vec,this);
    //vectorlayerproperties->show();
    //
    // qDebug()<<"Vertex start";
    // QgsVertexMarker* mEdgeCenterMarker = new QgsVertexMarker( &mMapCanvas );
    // mEdgeCenterMarker->setIconType( QgsVertexMarker::ICON_CIRCLE );
    // mEdgeCenterMarker->setColor( Qt::red );
    // mEdgeCenterMarker->setIconSize( QgsGuiUtils::scaleIconSize( 10 ) );
    // mEdgeCenterMarker->setPenWidth( QgsGuiUtils::scaleIconSize( 3 ) );
    // mEdgeCenterMarker->setCenter(QgsPointXY(vec->selectedFeatures().begin()->geometry().vertexAt(1)));
    // mEdgeCenterMarker->setVisible( true );
    //


//    QgsFeatureIterator it=vec->getFeatures();
//    it.rewind();
//    QgsFeature fea;
//    while (it.nextFeature(fea))
//    {
//        qDebug()<<"area:"<<fea.geometry().area();
//        for(int i=0;i<fea.attributes().size();i++)
//        {
//            qDebug()<<fea.attributes()[i];
//        }
//    }

    qDebug()<<vec->selectedFeatureCount();

//    QgsAdvancedDigitizingDockWidget* mcadwidget=new QgsAdvancedDigitizingDockWidget(&mMapCanvas,this);
//    QgsMapToolDigitizeFeature* createfeeature=new QgsMapToolDigitizeFeature(&mMapCanvas,mcadwidget,QgsMapToolCapture::CaptureNone);
//    connect(createfeeature,&QgsMapToolDigitizeFeature::digitizingCompleted,this,&Riskgis::actionspecialtestslot);
//    mMapCanvas.setMapTool(createfeeature);
//    if(vec->startEditing())
//    {
//        qDebug()<<"开始编辑";
//    }
//    else {
//        qDebug()<<"不可编辑";
//    }



    //vec->beginEditCommand("Add feature");

//    vec->selectAll();
//    qDebug()<<"select all";
    //mMapCanvas.setCachingEnabled(true);

    //mMapCanvas.refresh();
//    QSet<QgsFeatureId> id;
//    id.insert(QgsFeatureId(1));
//    id.insert(QgsFeatureId(2));
//    vec->selectByIds(QgsFeatureIds(id));
//    QgsFeature it=vec->getFeature(QgsFeatureId(1));
//    qDebug()<<vec->fields().at(2).displayName();
//    qDebug()<<vec->fields().count();
//    qDebug()<<it.attributeCount();
//    qDebug()<<it.attributes().at(1);
//    qDebug()<<it.attributes().at(2);
//    qDebug()<<it.attributes().at(3);
//    auto bb=QgsApplication::instance()->processingRegistry()->algorithmById("native:slope");
//    if(bb==nullptr)
//    {
//        qDebug()<<"native:buffer null";
//    }
//    auto parameters=bb->parameterDefinitions();
//    for(auto e:parameters)
//    {
//        qDebug()<<e->description();
//    }
//    auto aa=QgsApplication::instance()->processingRegistry()->algorithms();
//    if(aa.empty())
//    {
//        qDebug()<<"empty";
//    }
//    for(auto &e:aa)
//    {
//        qDebug()<<e->name();
//    }

//    auto aa=new QgsProcessingToolboxTreeView(this);
//    auto ccc=new QgsDockWidget(this);
//    qDebug()<<"toolbox";
//    //auto dd=QWidget(this);
//    //dd.layout()->addWidget(aa);
//    ccc->setWidget(aa);
//    qDebug()<<"setwidget";
//    addDockWidget(Qt::RightDockWidgetArea,ccc);
//    qDebug()<<"adddockwidget";
    //栅格文件test
//    QgsRasterLayer* ras=dynamic_cast<QgsRasterLayer*>(activeLayer());
//    if(ras==nullptr)
//    {
//        return;
//    }
//    qDebug()<<"success";

//    QgsRasterBlock* block=ras->dataProvider()->block(1,QgsRectangle(),500,500);
//    if(block==nullptr)
//    {
//        qDebug()<<"block nullptr";
//        return;
//    }
//    qDebug()<<ras->dataProvider()->dpi();
//    qDebug()<<block->height();
//    qDebug()<<block->width();
//    qDebug()<<block->isValid();
//    qDebug()<<block->hasNoDataValue();
//    if(block->dataType()== Qgis::DataType::Float32)
//    {
//        qDebug()<<"float32";
//    }
//    char* aa=block->bits();
//    qDebug()<<"bits";
//    if(aa==nullptr)
//    {
//        qDebug()<<"null";
//        return;
//    }
//    float* bb=(float*)aa;
//    qDebug()<<ras->extent().width();
//    qDebug()<<ras->extent().height();
//    qDebug()<<ras->dataProvider()->extent().width();
//    qDebug()<<ras->dataProvider()->extent().height();
//    qDebug()<<ras->dataProvider()->xSize();
//    qDebug()<<ras->dataProvider()->ySize();
//    qDebug()<<bb[300*500+300];
//    qDebug()<<block->value(300,300);


}

void Riskgis::actionspecialtestslot(const QgsFeature &f)
{
    qDebug()<<"开始";
    qDebug()<<f.geometry().area();
}


void Riskgis::on_actiontoggleEditing_toggled(bool arg1)
{
    toggleEditing(activeLayer());
    activateDeactivateRelatedAction(activeLayer());

}
void Riskgis::on_mActionAddFeature_triggered()
{
    m_mapToolAddFeature->setCurrentCaptureTechnique(Qgis::CaptureTechnique::StraightSegments);
    m_mapToolAddFeature->setLayer(activeLayer());
    mMapCanvas.setMapTool(m_mapToolAddFeature);
}

